package com.novoda.runbuddy.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public abstract class IRBContentProvider extends RunBuddyContentProviderFactory {
	private volatile static ContentProvider		uInstance;
	protected volatile static SQLiteOpenHelper	mOpenHelper;

	/*
	 * We ensure we only have one instance of the global content provider and db
	 * for all subclasses
	 */
	public IRBContentProvider(ContentProvider cp, SQLiteOpenHelper mDBe) {
		if (uInstance == null) {
			synchronized (IRBContentProvider.class) {
				if (uInstance == null) {
					uInstance = cp;
				}
			}
		}

		if (mOpenHelper == null) {
			synchronized (IRBContentProvider.class) {
				if (mOpenHelper == null) {
					mOpenHelper = mDBe;
				}
			}
		}
	}

	/************** Methods shared across all ContentProviders should be set here */

	/**
	 * The easiest way to add a geoLocation point into the DB.
	 * 
	 * @param latitude
	 * @param longitude
	 * @return the _id of the newly created geoLocation point. Most probably
	 *         used as foreign key for another table
	 */
	protected long createGeoLocation(long latitude, long longitude) {
		long geoLocationRowID;
		ContentValues geoValues = new ContentValues();
		geoValues.put("latitude", latitude);
		geoValues.put("longitude", longitude);
		geoLocationRowID = mOpenHelper.getWritableDatabase().insert("geoLocation", "name", geoValues);
		return geoLocationRowID;
	}

	protected long insertGeoLocation(long latitude, long longitude, long altitude) {
		long geoLocationRowID;
		ContentValues geoValues = new ContentValues();
		geoValues.put("latitude", latitude);
		geoValues.put("longitude", longitude);
		geoValues.put("altitude", altitude);
		geoLocationRowID = mOpenHelper.getWritableDatabase().insert("geoLocation", "name", geoValues);
		return geoLocationRowID;
	}

	public abstract int delete(Uri uri, String selection, String[] selectionArgs);

	public abstract String getType(Uri uri);

	public abstract Uri insert(Uri uri, ContentValues values);

	public abstract Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);

	public abstract int update(Uri uri, ContentValues values, String selection, String[] selectionArgs);

	public Context getContext() {
		return uInstance.getContext();
	}

	public SQLiteDatabase getReadableDatabase() {
		return mOpenHelper.getReadableDatabase();
	}

	public SQLiteDatabase getWritableDatabase() {
		return mOpenHelper.getWritableDatabase();
	}
}
